<template>
  <div class="h5-customer-detail">
    <ActivityH5
      :CustomerValue="CustomerValue"
      @getCustomerValue="getCustomerValue"
      @closeDrawer="closeDrawer"
      @prev="prev"
      @next="next"
      @refreshPage="emit('refreshData')"
      :tagMap="tagMap"
      :isLoad="isLoading"
      :isPool="isPool"
      :validateWrite="validateWrite"
      :validateOwnerUser="validateOwnerUser"
      :moduleOption="moduleOption"
    />
    <!-- 详细资料 -->
    <DetailsH5 v-if="selectTag == 1" :CustomerValue="CustomerValue" />
    <SystemCustomerH5 v-if="selectTag == 1" :CustomerValue="CustomerValue" />
    <!-- ai摘要 -->
    <AiSummaryH5 v-if="selectTag == 11" :clueValue="CustomerValue" />
    <!-- 状态 -->
    <StatusCustomerH5
      @getCustomerValue="getCustomerValue"
      v-if="selectTag == 0"
      :CustomerValue="CustomerValue"
    />
    <!-- 跟进记录 -->
    <FlowUpH5
      v-if="selectTag == 0"
      :clueValue="CustomerValue"
      :bizType="BizTypeEnum.CRM_CUSTOMER"
    />
    <!-- 操作日志 -->
    <LogH5
      v-if="selectTag == 10"
      :clueValue="CustomerValue"
      :id="CustomerValue.id"
      :bizType="BizTypeEnum.CRM_CUSTOMER"
    />
    <!-- 团队成员 -->
    <teamMembersH5
      v-if="selectTag == 3"
      :bizId="CustomerValue.id"
      :bizType="BizTypeEnum.CRM_CUSTOMER"
      :showAction="true"
    />
    <!-- 联系人 -->
    <ContactListH5
      v-if="selectTag == 2"
      :biz-id="CustomerValue.id"
      :customer-id="CustomerValue.id"
      :biz-type="BizTypeEnum.CRM_CUSTOMER"
    />
    <!-- 商机 -->
    <BusinessListH5
      v-if="selectTag == 5"
      :biz-id="CustomerValue.id"
      :customer-id="CustomerValue.id"
      :biz-type="BizTypeEnum.CRM_CUSTOMER"
    />
    <!-- 合同 -->
    <ContractListH5
      v-if="selectTag == 6"
      :biz-id="CustomerValue.id"
      :customer-id="CustomerValue.id"
      :biz-type="BizTypeEnum.CRM_CUSTOMER"
    />
    <!-- 回款-->
    <ReceivableListH5
      v-if="selectTag == 7"
      ref="receivableListRef"
      :customer-id="CustomerValue.id"
    />
    <!-- 回款计划 -->
    <ReceivablePlanListH5
      v-if="selectTag == 9"
      :customer-id="CustomerValue.id"
      @create-receivable="createReceivable"
    />
  </div>

  <!-- H5适配的弹窗 -->
  <el-drawer v-model="dialogVisible" title="关联企业微信" direction="btt" size="80%">
    <div class="h5-dialog-content">
      <div class="wecom-list" v-infinite-scroll="onLoad" :infinite-scroll-disabled="finished">
        <div
          v-for="item in gridData"
          :key="item.id"
          class="wecom-item"
          @click="selectWecomItem(item)"
          :class="{ selected: changItem && changItem.externalUserId === item.externalUserId }"
        >
          <div class="item-left">
            <div class="customer-type-icon">
              <svg v-if="item.type == 1" class="icon" viewBox="0 0 1229 1024">
                <path
                  d="M702.72 849.92c-76.8 30.72-158.72 35.84-240.64 30.72-35.84-5.12-71.68-10.24-107.52-20.48-5.12 0-10.24 0-15.36 5.12-46.08 20.48-92.16 46.08-133.12 66.56-15.36 10.24-30.72 10.24-46.08 0s-15.36-25.6-15.36-46.08c10.24-35.84 10.24-71.68 15.36-107.52 0-5.12-5.12-10.24-5.12-15.36-51.2-51.2-92.16-102.4-122.88-168.96-51.2-122.88-40.96-245.76 30.72-358.4C134.4 112.64 247.04 46.08 380.16 15.36S641.28 0 764.16 61.44c112.64 56.32 194.56 143.36 230.4 266.24 15.36 46.08 20.48 92.16 15.36 138.24-25.6-25.6-56.32-30.72-87.04-15.36 0-30.72 0-61.44-10.24-92.16-20.48-71.68-61.44-128-112.64-174.08-87.04-71.68-194.56-102.4-307.2-102.4-117.76 10.24-220.16 51.2-302.08 133.12-66.56 66.56-102.4 148.48-97.28 245.76 5.12 81.92 40.96 148.48 92.16 204.8l40.96 40.96c20.48 15.36 25.6 30.72 15.36 51.2-5.12 20.48-10.24 46.08-15.36 66.56 0 5.12-5.12 10.24 0 10.24 5.12 5.12 10.24 0 10.24 0 25.6-15.36 56.32-30.72 81.92-51.2 15.36-10.24 30.72-10.24 51.2-5.12 87.04 25.6 179.2 25.6 266.24 0 5.12 0 10.24-5.12 10.24 5.12 10.24 30.72 25.6 51.2 56.32 66.56z"
                  fill="#0082EF"
                ></path>
              </svg>
              <svg v-if="item.type == 2" class="icon" viewBox="0 0 1024 1024">
                <path
                  d="M337.387283 341.82659c-17.757225 0-35.514451 11.83815-35.514451 29.595375s17.757225 29.595376 35.514451 29.595376 29.595376-11.83815 29.595376-29.595376c0-18.49711-11.83815-29.595376-29.595376-29.595375z"
                  fill="#28C445"
                ></path>
              </svg>
            </div>
            <div class="item-info">
              <div class="item-name">{{ item.name }}</div>
              <div class="item-corp">{{ item.corpName }}</div>
            </div>
          </div>
          <div class="item-right">
            <el-radio v-model="selectedWecom" :label="item.externalUserId" />
          </div>
        </div>
      </div>
      <div v-if="loading" class="loading-text">加载中...</div>
      <div v-if="finished" class="finished-text">没有更多了</div>
    </div>
    <template #footer>
      <el-button type="primary" @click="confrimWeCom" style="width: 100%">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup>
import { dateFormatter } from '@/utils/formatTime'
import { customFieldHeadList } from '@/api/crm/module/index'
import * as CustomerApi from '@/api/crm/customer'
import * as customerTagApi from '@/api/crm/customerTagConfig/index'
import * as PermissionApi from '@/api/crm/permission'
import { BizTypeEnum } from '@/api/crm/permission'
import { useUserStoreWithOut } from '@/store/modules/user'
import FlowUpH5 from './flowH5.vue'
import LogH5 from './logH5.vue'
import teamMembersH5 from '@/views/crm/components/teamMembers/index.vue'
import ContactListH5 from '@/views/crm/contact/components/newContactList.vue'
import BusinessListH5 from '@/views/crm/business/components/newBusinessList.vue'
import ContractListH5 from '@/views/crm/contract/components/newContractList.vue'
import ReceivableListH5 from '@/views/crm/receivable/components/newReceivableList.vue'
import ReceivablePlanListH5 from '@/views/crm/receivable/plan/components/newReceivablePlanList.vue'
import * as weCustomerApi from '@/api/wecom/customer/index'
import { getWeCustomerPage } from '@/api/wecom/customer/index'
import StatusCustomerH5 from './statusH5.vue'
import DetailsH5 from './detailsH5.vue'
import SystemCustomerH5 from './systemH5.vue'
import ActivityH5 from './activityH5.vue'
import AiSummaryH5 from '@/views/crm/clue/detail/aiSummary.vue'

const queryParams = ref({
  pageNo: 1,
  pageSize: 10
})

const props = defineProps({
  selectTag: Number,
  id: String,
  nowIds: Array,
  moduleOption: Array
})
const emit = defineEmits(['setDrawer', 'refreshData'])
const customerId = ref('')
const CustomerValue = ref({})
const tagMap = ref([])
const isLoading = ref(false)

const teamMembersList = ref([])
const loading = ref(false)
const finished = ref(false)
const selectedWecom = ref('')

/** 查询列表 */
const getTeamMembers = async () => {
  loading.value = true
  try {
    const data = await PermissionApi.getPermissionList({
      bizType: BizTypeEnum.CRM_CUSTOMER,
      bizId: props.id
    })
    teamMembersList.value = data
  } finally {
    loading.value = false
  }
}

/** 从回款计划创建回款 */
const receivableListRef = ref()
const createReceivable = (planData) => {
  receivableListRef.value?.createReceivable(planData)
}

/**客户的详情*/
const getCustomerValue = async () => {
  try {
    isLoading.value = true
    const res = await CustomerApi.getCustomer(customerId.value)
    const filedResult = await customFieldHeadList({
      moduleId: customerId.value,
      tableType: '2'
    })
    if (filedResult) {
      res.detailFiled = filedResult.filter((item) => item.isShow == 1)
    }
    const results = await CustomerApi.getCustomerTag({ ids: [customerId.value] })
    res.labelList = results[customerId.value] || []
    CustomerValue.value = res
    if (CustomerValue.value.weCustomerId) getWeComDetail(CustomerValue.value.weCustomerId)
  } finally {
    isLoading.value = false
  }
}

/**标签列表*/
const getTagList = async () => {
  const { list } = await customerTagApi.getCustomerTagPage()
  tagMap.value = list
}

/**上一条*/
const prev = () => {
  const index = props.nowIds.indexOf(customerId.value) - 1
  if (props.nowIds[index]) {
    customerId.value = props.nowIds[index]
    getCustomerValue()
    getTeamMembers()
  } else {
    ElMessage.error('没有更多了')
  }
}

/**下一条*/
const next = () => {
  const index = props.nowIds.indexOf(customerId.value) + 1
  if (props.nowIds[index]) {
    customerId.value = props.nowIds[index]
    getCustomerValue()
    getTeamMembers()
  } else {
    ElMessage.error('没有更多了')
  }
}

watch(
  () => props.id,
  (val) => {
    if (val) {
      customerId.value = val
      getCustomerValue()
      getTeamMembers()
      getTagList()
    }
  },
  { deep: true, immediate: true }
)

/**关闭*/
const closeDrawer = () => {
  emit('setDrawer')
}

// 校验负责人权限和编辑权限
const validateOwnerUser = ref(false)
const validateWrite = ref(false)
const isPool = ref(false)
const userStore = useUserStoreWithOut()

const dialogVisible = ref(false)
const gridData = ref([])
const totals = ref(0)

// 显示关联企微
const showWeCom = async () => {
  if (isPool.value) return
  queryParams.value.pageNo = 1
  gridData.value = []
  finished.value = false
  const { list, total } = await getWeCustomerPage(queryParams.value)
  gridData.value = list
  totals.value = total
  dialogVisible.value = true
}

const wecomFollowUserList = ref([])
const userItem = ref({})

/** 查询企微客户详情*/
const getWeComDetail = async (id) => {
  const data = await weCustomerApi.getWeCustomerId(id)
  userItem.value = data
  if (data && data.followUserList) {
    wecomFollowUserList.value = data.followUserList
  } else {
    wecomFollowUserList.value = []
  }
}

const changItem = ref(null)

// H5选择企微客户
const selectWecomItem = (item) => {
  changItem.value = item
  selectedWecom.value = item.externalUserId
}

// H5加载更多
const onLoad = async () => {
  if (finished.value || loading.value) return

  loading.value = true
  queryParams.value.pageNo++

  try {
    const { list } = await getWeCustomerPage(queryParams.value)

    if (list.length === 0) {
      finished.value = true
    } else {
      gridData.value = [...gridData.value, ...list]
    }
  } finally {
    loading.value = false
  }
}

// 确定提交
const confrimWeCom = async () => {
  if (changItem.value) {
    dialogVisible.value = false
    const data = await CustomerApi.updateCustomerWeCom({
      id: props.id,
      weCustomerId: changItem.value.externalUserId
    })
    if (data) {
      ElMessage.success('操作成功')
      getWeComDetail(props.id)
    }
  } else {
    ElMessage.warning('请选择关联的企业微信')
  }
}

watch(
  () => teamMembersList.value,
  (newArr) => {
    isPool.value = false
    validateOwnerUser.value = false
    validateWrite.value = false
    if (newArr.length > 0) {
      isPool.value = !newArr.some((item) => item.level === PermissionApi.PermissionLevelEnum.OWNER)
      const userId = userStore.getUser?.id
      newArr
        .filter((item) => item.userId === userId)
        .forEach((item) => {
          if (item.level === PermissionApi.PermissionLevelEnum.OWNER) {
            validateOwnerUser.value = true
            validateWrite.value = true
          } else if (item.level === PermissionApi.PermissionLevelEnum.WRITE) {
            validateWrite.value = true
          }
        })
    } else {
      isPool.value = true
    }
  },
  {
    immediate: true,
    deep: true
  }
)
</script>

<style lang="scss" scoped>
.h5-customer-detail {
  padding: 0;
  background: #f5f5f5;
  min-height: 100vh;
}

.h5-dialog-content {
  height: 100%;

  .wecom-list {
    height: calc(100% - 60px);
    overflow-y: auto;

    .wecom-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px 16px;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;

      &:hover {
        background-color: #f5f7fa;
      }

      &.selected {
        background-color: #ecf5ff;
      }

      .item-left {
        display: flex;
        align-items: center;
        flex: 1;

        .customer-type-icon {
          width: 24px;
          height: 24px;
          margin-right: 12px;

          .icon {
            width: 100%;
            height: 100%;
          }
        }

        .item-info {
          .item-name {
            font-size: 14px;
            color: #303133;
            margin-bottom: 4px;
          }

          .item-corp {
            font-size: 12px;
            color: #909399;
          }
        }
      }

      .item-right {
        margin-left: 12px;
      }
    }
  }

  .loading-text,
  .finished-text {
    text-align: center;
    padding: 16px;
    color: #909399;
    font-size: 14px;
  }
}
</style>
